package com.icesoft.base.manager.security.impl;

import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.helper.SecurityUtils;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.helper.RespCode;
import com.icesoft.core.web.helper.RequestHold;
import com.icesoft.core.web.helper.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class DefaultAccessDeniedHandler extends AccessDeniedHandlerImpl {
    private static final String errorPage = "/error";

    public DefaultAccessDeniedHandler() {
        setErrorPage(errorPage);
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        AuthUser authUser = SecurityUtils.getUser();
        log.info("用户:[{}],访问请求：{}，被拦截：{}", authUser == null ? "null" : authUser.getUsername(), request.getRequestURI(), accessDeniedException.getMessage());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        if (RequestHold.isAjax(request)) {
            ResponseUtils.writeJson(response, Resp.error(RespCode.NO_PERMISSION, "拒绝访问"));
        } else {
            //交给ErrorHtmlController返回错误页面
            request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, HttpServletResponse.SC_FORBIDDEN);
            super.handle(request, response, accessDeniedException);
        }

    }
}
